package com.zxq.web.nettyhandler;


import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import com.zxq.exchange.enums.EFrame;
import com.zxq.exchange.model.ExchangeDTO;
import com.zxq.frame.TcpModBusFrame;
import com.zxq.frame.modbus.ModBusChannelContainer;
import com.zxq.frame.modbus.ModBusService;
import com.zxq.tcp.cache.TcpChannelCache;
import com.zxq.tcp.handler.dispatch.TCPDispatchHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TCPModBusDispatchHandler extends TCPDispatchHandler<TcpModBusFrame> {


    @Override
    protected ExchangeDTO decodeExchangeDTO() {
        String devId = TcpChannelCache.getDevId(channel);
        ModBusService modBusCrc =  ModBusChannelContainer.getModbusCrc(devId);
        int length =  modBusCrc.measureFrameLen();
        if (in.readableBytes() < length) {
            //log.info("当前可读数据不够，继续等待4。。");
            return null;
        }
        byte[] content = new byte[length];

        in.readBytes(content);
        //解锁发送数据
        boolean isLegal = modBusCrc.isLegalFrame(content);
        if(!isLegal) {
            log.info("channel:" + channel.toString() + " error:" +HexBin.encode(content));
            return null;
        }
        //解析后的欣喜，发送给平台
        ExchangeDTO exchangeDTO = new ExchangeDTO();
        exchangeDTO.setCmdHex(HexBin.encode(new byte[]{content[0]}));
        exchangeDTO.setData(content);
        return  exchangeDTO;
    }

    @Override
    protected TcpModBusFrame produceFrame(String cmd_id, byte[] data) {

        return null;
    }

    @Override
    protected EFrame getTcpFrame() {
        return EFrame.modbus;
    }


    @Override
    public boolean isThisFrame() {

         byte primaryByte = in.readByte();
         byte secondByte = in.readByte();
        // log.info("hex:" + HexBin.encode(new byte[]{primaryByte,secondByte}));
         in.resetReaderIndex();
         String devId = TcpChannelCache.getDevId(channel);
         ModBusService modBusCrc = ModBusChannelContainer.getModbusCrc(devId);
         if(modBusCrc == null)
             return false;
         return modBusCrc.isModelBus(primaryByte,secondByte);
    }





}
